import 'dart:async';
import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ringtone_player/flutter_ringtone_player.dart';
import 'package:videotop/sql/databasehelper.dart';
import 'package:videotop/sql/msg_table.dart';
import 'package:videotop/sql/user_table.dart';
import 'package:videotop/util.dart';
import '../App_ID.dart';
import '../evenbus.dart';
import '../mycolor.dart';
import '../myinfo.dart';
import '../screen_service.dart';

class VideoPage extends StatefulWidget {
  /// non-modifiable channel name of the page
  String channelName;

  /// non-modifiable client role of the page
  ClientRole role;

  String nickname;

  bool initiative;

  int uid;

  int price;

  String icon;

  String country;

  String countrycode;

  String birth;

  int vip;

  /// Creates a call page with given channel name.
  VideoPage(this.initiative,
      {
      this.channelName,
      this.role,
      this.price,
      this.uid,
      this.nickname = '',
      this.icon,
      this.countrycode = 'us',
      this.vip = 0,
      this.birth,
      this.country = ''});

  @override
  _VideoPageState createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage> with SingleTickerProviderStateMixin{

  final _users = <int>[];
  final _infoStrings = <String>[];
  bool muted = false;

  bool isyingchang = true;
  bool isjoin = false;

  int time = 0; // 接通总时长
  int endtime = 0; //倒计时
  bool daojishishow = false;
  int dialogtime = 5; //闪烁时长
  bool dialogshow = false;// 是否闪烁
  Timer timer;

  String fen = '';
  String miao = '';
  bool show = false;
  bool endshow = false;

  bool isbreak = true;

  bool isoff = true; // 时候接通视频  true 没接通自动挂断

  bool isdispose = false; //如果自己挂断，30秒就不弹出toast

  AnimationController _controller;// 闪烁动画
  Animation _animation;
  int endmin = 3; // 3 2 1 剩余分钟

  bool endcancel = false;//金币不够挂断判断
  Util util;
  MyInfo myInfo;
  @override
  void initState() {
    if (widget.initiative) {
      if (widget.role == ClientRole.Broadcaster) {
        util.getisvideo(widget.uid).then((value) {
          if(value){
            util.showToast('The user is busy');
            Navigator.pop(context);
          }else{
            getNativevideo();
          }
        });
      }
    }
    super.initState();
    initialize();
    //播放铃声
    FlutterRingtonePlayer.playRingtone(looping: true);

    bus.on('offvideo', (arg) {
      if (arg == 1) {
        onGetUserEndMessage();
      } else {
        util.showToast('The other party is talking');
        Navigator.of(context).pop();
      }
      bus.off('offvideo');
    });

    _controller = AnimationController(
        vsync: this,
        duration: Duration(seconds: 1)
    );

    _animation = Tween(begin: 0.0, end: 1.0).animate(_controller);
    _controller.forward();
    setState(() {});
    _animation.addStatusListener((status) {
      if(status == AnimationStatus.completed){
        _controller.reverse();
      }else if(status == AnimationStatus.dismissed){
        _controller.forward();
        setState(() {

        });
      }
    });

  }


  @override
  void dispose() {
    isdispose = true;
    FlutterRingtonePlayer.stop();
    timer?.cancel();
    _users.clear();
    AgoraRtcEngine.leaveChannel();
    AgoraRtcEngine.destroy();
    util.setUpdateVideoNow(myInfo.uid,widget.uid, 0);
    _controller.dispose();
    super.dispose();
  }

  getNativevideo() async {
    util.getNativeYuid(widget.uid).then((value) {
      util.sendTextMessage('打开视频${widget.channelName}');
      Future.delayed(Duration(seconds: 30)).then((value){
        if(isoff && !isdispose){
          util.showToast('${widget.nickname} may be busy,Try again later');
          Navigator.pop(context);
        }
      });
    });

  }

  //发送 用户挂断消息
  void sendEndMessage() async {
    doSendMsg(
        '${time} s',
        widget.uid,
        DateTime.now().millisecondsSinceEpoch.toString(),
        widget.icon,
        widget.nickname,
        widget.country,
        widget.countrycode,
        widget.vip,
        widget.price,
      widget.birth
    );
    util.sendTextMessage('挂断视频${time} s');
    if (mounted) Navigator.of(context).pop();
    // if(endcancel){
    //   Navigator.of(context)
    //       .push(MaterialPageRoute(builder: (context) => BuyGold()));
    // }
  }

  // 收到 对方挂断消息
  void onGetUserEndMessage() async {
    util.showToast('The other party has hung up');
    Navigator.of(context).pop();
  }

  void doSendMsg(String content, int uid, var times, String icon,
      String nickname, String country, String code, int vip, int price,String birth) async {
    var db = new DatabaseHelper();

    //保存用户
    UserTable user1 = await db.getItem(uid);
    if (user1 == null) {
      if (icon.isEmpty) {
        //请求服务器 获取icon 和nickname
        var map = await util.getBasicInfo(uid);
        icon = map['icon'];
        nickname = map['nickname'];
        vip = map['vip'];
        code = map['code'];
        birth = map['birth'];
        country = map['country'];
      }
      UserTable user = new UserTable();
      user.uid = uid;
      user.times = times;
      user.uptime = DateTime.now().millisecondsSinceEpoch.toString();
      user.icon = icon;
      user.nickname = nickname;
      user.birth = birth;
      user.country = country;
      user.vip = vip;
      user.code = code;
      user.price = price;
      db.saveItemUser(user);
    } else {
      var nowtime = DateTime.now();
      if (DateTime.fromMillisecondsSinceEpoch(int.parse(user1.uptime))
          .add(Duration(hours: 1))
          .isBefore(nowtime)) {
        UserTable user = new UserTable();
        user.uid = user.uid;
        user.times = DateTime.now().millisecondsSinceEpoch.toString();
        user.icon = user.icon;
        user.uptime = DateTime.now().millisecondsSinceEpoch.toString();
        user.nickname = user.nickname;
        user.country = user.country;
        user.birth = user.birth;
        user.vip = user.vip;
        user.code = user.code;
        user.price = user.price;
        db.updateUser(user);
      }
    }
    Msg msg = new Msg();
    msg.uid = uid;
    msg.state = 0;
    msg.times = times;
    msg.img = '';
    msg.video = content;
    msg.content = '';
    msg.type = 0;
    db.saveItemMsg(msg);
    //通知更新
    bus.emit('refresh', 1);
    //通知聊天UI
    bus.emit('chat', msg);
  }

  Future<void> initialize() async {
    if(widget.icon == null){
      util.getBasicInfo(widget.uid).then((map){
        widget.icon = map['icon'];
        widget.country = map['country'];
        widget.countrycode = map['code'];
        widget.nickname = map['nickname'];
        widget.price = map['price'];
        widget.vip = map['vip'];
        widget.birth = map['birth'];
        setState(() {

        });
      });
    }
    await _initAgoraRtcEngine();
    _addAgoraEventHandlers();
    await AgoraRtcEngine.enableWebSdkInteroperability(true);
    VideoEncoderConfiguration configuration = VideoEncoderConfiguration();
    configuration.dimensions = Size(640, 480);
    await AgoraRtcEngine.setVideoEncoderConfiguration(configuration);
    if (widget.initiative) {
      joinChannel();
    }
  }

  joinChannel() async {
    await AgoraRtcEngine.joinChannel(
        null, widget.channelName, widget.channelName, widget.uid);
  }

  /// Create agora sdk instance and initialize
  Future<void> _initAgoraRtcEngine() async {
    await AgoraRtcEngine.create(APP_ID);
    await AgoraRtcEngine.enableVideo();
    await AgoraRtcEngine.setChannelProfile(ChannelProfile.Communication);
    await AgoraRtcEngine.setClientRole(widget.role);

    AgoraRtcEngine.disableAudio();
  }

  /// Add agora event handlers
  void _addAgoraEventHandlers() {
    AgoraRtcEngine.onError = (dynamic code) {
      setState(() {
        final info = 'onError: $code';
        _infoStrings.add(info);
      });
    };

    //加入房间成功
    AgoraRtcEngine.onJoinChannelSuccess = (
      String channel,
      int uid,
      int elapsed,
    ) {
      setState(() {
        final info = 'onJoinChannel: $channel, uid: $uid';
        _infoStrings.add(info);
      });

      isjoin = true;
      //AgoraRtcEngine.enableAudio();
      if (!widget.initiative) {
        AgoraRtcEngine.enableAudio();
      }
    };

    AgoraRtcEngine.onLeaveChannel = () {
      setState(() {
        _infoStrings.add('onLeaveChannel');
        _users.clear();
      });
    };

    AgoraRtcEngine.onUserJoined = (int uid, int elapsed) {
      FlutterRingtonePlayer.stop();
      isoff = false;
      if (widget.initiative) {
        AgoraRtcEngine.enableAudio();
      }
      setState(() {
        final info = 'userJoined: $uid';
        _infoStrings.add(info);
        _users.add(uid);
        isjoin = true;
      });
      getTimes();
    };

    AgoraRtcEngine.onUserOffline = (int uid, int reason) {
      setState(() {
        final info = 'userOffline: $uid';
        _infoStrings.add(info);
        _users.remove(uid);
      });
      timer.cancel();
//      Navigator.of(context).pop();
    };

    AgoraRtcEngine.onFirstRemoteVideoFrame = (
      int uid,
      int width,
      int height,
      int elapsed,
    ) {
      setState(() {
        final info = 'firstRemoteVideo: $uid ${width}x $height';
        _infoStrings.add(info);
      });
    };
  }

  getTimes() async {
    show = true;
    time = 0;
    bool once = true;
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      fen = (time ~/ 60).toString();
      if (fen.length == 1) fen = '0$fen';
      miao = (time % 60).toString();
      if (widget.initiative) {
        if (myInfo.gold > widget.price * 3) endshow = false;
        if (miao == '0') {
          if (myInfo.gold >= widget.price) {
            myInfo.gold -= widget.price;
            util.setGold(myInfo.gold, 2,myInfo.uid);
            if (myInfo.gold <= widget.price * 3) {
              endshow = true;
              if (once) {
                once = false;
                endtime = 60 * (myInfo.gold ~/ widget.price + 1);
              }
            } else {
              endshow = false;
            }
          } else {
            util.showToast('Insufficient balance');
            // 延时1s执行返回
            Future.delayed(Duration(seconds: 1), () {
              endcancel = true;
              _onCallEnd();
            });
          }
        }
      }
      if (miao.length == 1) miao = '0$miao';
      if(endtime == 10){
        daojishishow = true;
      }
      if (mounted) setState(() {});
      endtime--;
      if(endtime  < 0)
        endtime = 0;
      time++;
      if (endtime == 179 || endtime == 119 || endtime == 59) {
        dialogshow = true;
        dialogtime = 5;
        if(endtime == 179)
          endmin = 3;
        if(endtime == 119)
          endmin = 2;
        if(endtime == 59)
          endmin = 1;
      }
      dialogtime--;
      if (dialogtime == 0) {
        dialogshow = false;
      }
    });
  }

  /// Helper function to get list of native views
  List<Widget> _getRenderViews() {
    final List<AgoraRenderWidget> list = [];
    if (widget.role == ClientRole.Broadcaster) {
      list.add(AgoraRenderWidget(0, local: true, preview: true));
    }
    _users.forEach((int uid) {
      list.add(AgoraRenderWidget(uid));
    });
    return list;
  }

  /// Video view wrapper
  Widget _videoView(view) {
    return Expanded(child: Container(child: view));
  }

  /// Video view row wrapper
  Widget _expandedVideoRow(List<Widget> views) {
    final wrappedViews = views.map<Widget>(_videoView).toList();
    return Expanded(
      child: Row(
        children: wrappedViews,
      ),
    );
  }

  /// Video layout wrapper
  Widget _viewRows() {
    final views = _getRenderViews();
    switch (views.length) {
      case 1:
        return Container(
            child: Column(
          children: <Widget>[_videoView(views[0])],
        ));
      case 2:
        return Container(
            child: Stack(
          alignment: Alignment.topRight,
          children: <Widget>[
//            _expandedVideoRow([views[0]]),
//            _expandedVideoRow([views[1]])
            Column(
              children: [_videoView(views[1])],
            ),
            Container(
              margin: EdgeInsets.only(right: 20, top: 70),
              width: 100,
              height: 150,
              child: views[0],
            ),
          ],
        ));
      case 3:
        return Container(
          child: Column(
            children: <Widget>[
              _expandedVideoRow(views.sublist(0, 2)),
              _expandedVideoRow(views.sublist(2, 3))
            ],
          ),
        );
      case 4:
        return Container(
            child: Column(
          children: <Widget>[
            _expandedVideoRow(views.sublist(0, 2)),
            _expandedVideoRow(views.sublist(2, 4))
          ],
        ));
      default:
    }
    return Container();
  }

  /// Toolbar layout
  Widget _toolbar() {
    if (widget.role == ClientRole.Audience) return Container();
    return Container(
      alignment: Alignment.bottomCenter,
      padding: const EdgeInsets.symmetric(vertical: 48),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          RaisedButton(
            onPressed: _onToggleMute,
            child: Icon(
              muted ? Icons.mic_off : Icons.mic,
              color: muted ? Colors.white : Color(0xff3F2C9F),
              size: 20.0,
            ),
            shape: CircleBorder(),
            elevation: 2.0,
            color: muted ? MyColor.theme : Colors.white,
            padding: const EdgeInsets.all(12.0),
          ),
          RaisedButton(
            onPressed: () {
              _onCallEnd();
            },
            child: Icon(
              Icons.call_end,
              color: Colors.white,
              size: 35.0,
            ),
            shape: CircleBorder(),
            elevation: 2.0,
            color: Colors.redAccent,
            padding: const EdgeInsets.all(15.0),
          ),
          isbeijiao(),
          RaisedButton(
            onPressed: _onSwitchCamera,
            child: Image.asset(
              'assets/image/qiehuan.png',
              height: 20,width: 35,
            ),
            shape: CircleBorder(),
            elevation: 2.0,
            color: Colors.white,
            padding: const EdgeInsets.all(12.0),
          )
        ],
      ),
    );
  }

  Widget showTime2() {
    return Visibility(
      visible: show,
      child: Container(
          alignment: Alignment.bottomCenter,
          padding: const EdgeInsets.symmetric(vertical: 140),
          child: Container(
            height: 45,
            width: 120,
            padding: EdgeInsets.only(left: 15, right: 15),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular((30)),
              color: Color(0x5f3F2C9F),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'assets/image/videotime.png',
                  width: 30,
                  height: 30,
                ),
                SizedBox(
                  width: 5,
                ),
                Text(
                  '$fen:$miao',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 15,
                      fontFamily: 'my_medium'),
                ),
              ],
            ),
          )
      ),
    );
  }

  Widget showTime() {
    return Visibility(
      visible: show,
      child: Align(
        alignment: Alignment.bottomCenter,
        child: Container(
          margin: const EdgeInsets.symmetric(vertical: 130),
          child: Text(
            '$fen:$miao',
            style: TextStyle(color: Colors.white, fontSize: 15),
          ),
        )
      ),
    );
  }

  chongzhi() {
    // showModalBottomSheet(
    //   context: context,
    //   backgroundColor: Colors.transparent,
    //   builder: (BuildContext context) {
    //     return Container(
    //       // height: ScreenService.height * 0.5,
    //       child: ChatByGOld(),
    //     );
    //   },
    // );
  }

  Widget isbeijiao() {
    if (widget.initiative) {
      return Visibility(
        visible: false,
        child: RaisedButton(
          onPressed: () {},
        ),
      );
    } else {
      return Visibility(
        visible: isyingchang,
        child: RaisedButton(
          onPressed: () {
            util.setUpdateVideoNow(myInfo.uid,widget.uid, 1);
            isyingchang = false;
            setState(() {});
            FlutterRingtonePlayer.stop();
            joinChannel();
          },
          child: Icon(
            Icons.call,
            color: Colors.white,
            size: 35.0,
          ),
          shape: CircleBorder(),
          elevation: 2.0,
          color: Colors.green,
          padding: const EdgeInsets.all(15.0),
        ),
      );
    }
  }

  Widget fasong(){
    if(widget.initiative){
      return Align(
        alignment: Alignment.bottomCenter,
        child: Container(
          margin: EdgeInsets.only(bottom: 48),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: _onToggleMute,
                      child: muted ? Image.asset(
                        'assets/image/mic_off.png',
                        height: 50,width: 50,
                      ):Image.asset(
                        'assets/image/mic.png',
                        height: 50,width: 50,
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      'Mute',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 12
                      ),
                    )
                  ],
                ),
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () {
                        _onCallEnd();
                      },
                      child: Image.asset(
                        'assets/image/guaduan.png',
                        height: 50,width: 50,
                      )
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      'Hang Up',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 12
                      ),
                    )
                  ],
                ),
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: _onSwitchCamera,
                      child: Image.asset(
                        'assets/image/qiehuan.png',
                        height: 50,width: 50,
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      'Switch Camera',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 12
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        )
      );
    }else{
      if(isyingchang){
        return Stack(
          children: [
            Positioned(
              bottom: 48,
              left: 40,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  GestureDetector(
                      onTap: () {
                        _onCallEnd();
                      },
                      child: Image.asset(
                        'assets/image/guaduan.png',
                        height: 50,width: 50,
                      )
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    'Hang Up',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 12
                    ),
                  )
                ],
              ),
            ),
            Positioned(
              bottom: 48,
              right: 40,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  GestureDetector(
                    onTap: _onSwitchCamera,
                    child: Image.asset(
                      'assets/image/qiehuan2.png',
                      height: 50,width: 50,
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    'Switch Camera',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 12
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  GestureDetector(
                    onTap: () {
                      util.setUpdateVideoNow(myInfo.uid,widget.uid, 1);
                      isyingchang = false;
                      setState(() {});
                      FlutterRingtonePlayer.stop();
                      joinChannel();
                    },
                    child: Image.asset(
                      'assets/image/jieting.png',
                      height: 50,width: 50,
                    )
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    'Accept',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 12
                    ),
                  )
                ],
              ),
            )
          ],
        );
      }else{
        return Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            margin: EdgeInsets.only(bottom: 48),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      GestureDetector(
                        onTap: _onToggleMute,
                        child: muted ? Image.asset(
                          'assets/image/mic_off.png',
                          height: 50,width: 50,
                        ):Image.asset(
                          'assets/image/mic.png',
                          height: 50,width: 50,
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        'Mute',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 12
                        ),
                      )
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      GestureDetector(
                          onTap: () {
                            _onCallEnd();
                          },
                          child: Image.asset(
                            'assets/image/guaduan.png',
                            height: 50,width: 50,
                          )
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        'Hang Up',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 12
                        ),
                      )
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      GestureDetector(
                        onTap: _onSwitchCamera,
                        child: Image.asset(
                          'assets/image/qiehuan.png',
                          height: 50,width: 50,
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        'Switch Camera',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 12
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }
  }

  void _onCallEnd() async {
    isbreak = false;
    if (time != 0) {
      List<String> id = widget.channelName.split('_');
      int dur = time ~/ 60;
      if (dur == 0) {
        dur = 1;
      }
      int price = myInfo.price;
      if (widget.channelName.startsWith(myInfo.uid.toString()))
        price = widget.price;
      // if (myInfo.vip == -100 && widget.vip == -100) {
      // } else {
      //   util.videotime(
      //       int.parse(id[0]), int.parse(id[1]), dur, price, dur * price);
      // }
    }
    // if (util.isVideo) await util.getNativeYuid(widget.uid);
    sendEndMessage();
  }

  void _onToggleMute() {
    setState(() {
      muted = !muted;
    });
    AgoraRtcEngine.muteLocalAudioStream(muted);
  }

  void _onSwitchCamera() {
    AgoraRtcEngine.switchCamera();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        if (isbreak) _onCallEnd();
      },
      child: Scaffold(
        backgroundColor: Colors.black,
        body: Center(
          child: Stack(
            children: <Widget>[
              _viewRows(),
              Container(
                height: ScreenService.height,
                width: ScreenService.width,
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        colors: [
                          Color(0x81000000),
                          Colors.black45,
                          Colors.black38,
                          Colors.black26,
                          Colors.black12,
                          Color(0x19000000)
                        ],
                        begin: Alignment.bottomCenter,
                        end: Alignment.topCenter
                    )
                ),
              ),
              Center(
                child: Visibility(
                  visible: daojishishow,
                  child: Text(
                    '$endtime',
                    style: TextStyle(
                        fontSize: 90,
                        fontWeight: FontWeight.bold,
                        color: Color(0xFFFFFFFF),
                        fontFamily: 'my_bold'
                    ),
                  ),
                )
              ),
              // _toolbar(),
              showTime(),
              // endTime(),
              top(),
              Positioned(
                top: 120,left: 30,
                child: InkWell(
                  onTap: chongzhi,
                  child: Image.asset(
                    'assets/image/coins.png',
                    height: 45,width: 45,
                  ),
                )
              ),
              Center(
                child: Visibility(
                  visible: dialogshow,
                  child:shansuo()
                ),
              ),
              fasong(),
            ],
          ),
        ),
      ),
    );
  }

  Widget top() {
    return Positioned(
      top: 50,
      left: 30,
      child: Row(
        children: <Widget>[
          ClipOval(
            child: Container(
              height: 50,
              width: 50,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  Container(
                    height: 50,
                    width: 50,
                    color: Color(0xff272443),
                    child: Center(
                      child: Image.asset(
                        'assets/image/space_bg.png',
                        width: 25,
                        height: 25,
                      ),
                    ),
                  ),
                  CachedNetworkImage(
                    imageUrl: '${widget.icon}?x-oss-process=image/resize,h_200',
                    height: 50,
                    width: 50,
                    fit: BoxFit.cover,
                  )
                ],
              ),
              color: Colors.grey[200],
            ),
          ),
          const SizedBox(
            width: 8,
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                constraints: BoxConstraints(maxWidth: ScreenService.width / 5),
                child: Text(
                  '${widget.nickname}',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontFamily: 'iconfont',
                    fontSize: 15,
                  ),
                ),
              ),
              const SizedBox(
                height: 5,
              ),
              Row(
                children: [
                  Container(
                    padding:
                        EdgeInsets.only(top: 2, bottom: 2, left: 5, right: 5),
                    child: Row(
                      children: [
                        ClipOval(
                          child: Image.asset(
                            'assets/images/flags/${widget.countrycode}.png',
                            package: 'ola_like_country_picker',
                            width: 15,
                            height: 15,
                            fit: BoxFit.cover,
                          ),
                        ),
                        const SizedBox(
                          width: 5,
                        ),
                        Text(
                          '${widget.country}',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                              fontFamily: 'iconfont'),
                        ),
                      ],
                    ),
                    decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.circular(10)),
                  ),
                  const SizedBox(
                    width: 5,
                  ),
                  Container(
                    padding:
                        EdgeInsets.only(top: 2, bottom: 2, left: 5, right: 5),
                    child: Row(
                      children: [
                        ClipOval(
                          child: Image.asset(
                            'assets/image/vipl.png',
                            width: 15,
                            height: 15,
                            fit: BoxFit.cover,
                          ),
                        ),
                        const SizedBox(
                          width: 5,
                        ),
                        Text(
                          widget.vip == -100 ? 'Lv12' : 'Lv${widget.vip}',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                              fontFamily: 'iconfont'),
                        ),
                      ],
                    ),
                    decoration: BoxDecoration(
                        color: Colors.pink,
                        borderRadius: BorderRadius.circular(10)),
                  )
                ],
              ),
            ],
          )
        ],
      ),
    );
  }
  Widget shansuo(){
    return FadeTransition(
      opacity: _animation,
      child: Container(
        margin: EdgeInsets.only(left: 20,right: 20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              // crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Image.asset(
                  'assets/image/coins.png',
                  height: 18,width: 18,
                ),
                Text(
                  'Not enough,',
                  style: TextStyle(
                      fontSize: 15,
                      color: Colors.white
                  ),
                ),
              ],
            ),
            Text(
              'Video chat only $endmin min',
              style: TextStyle(
                  fontSize: 15,
                  color: Colors.white
              ),
            ),
          ],
        )
      ),
    );
  }
}
